package nl.hva.three2learn.controller
{
	import flash.events.NetStatusEvent;
	import flash.events.SyncEvent;

	import flash.net.NetConnection;
	import flash.net.SharedObject;

	import nl.hva.three2learn.Variables;

	import nl.hva.three2learn.controller.ChatController;

	import mx.controls.Alert;

	public class ApplicationHandler
	{
		private var _nc:NetConnection;

		private var _blackboardSO:SharedObject;

		private var _controller:ChatController;

		public function ApplicationHandler(controller:ChatController)
		{
			_controller = controller;
		}

		public function doInit():void 
		{
			_nc = new NetConnection();

			var callbacks:Object = getCallbacks();
			callbacks._receiveMessage = _receiveMessage;

			_nc.client = callbacks;

			var info:Object = { name: Variables.name, isTeacher: isTeacher };

			_nc.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);

			_nc.connect("rtmp://" + STRINGS::host + "/livesession/" + Variables.instance, null, info);
		}

		public final function sendMessage(message:String):void
		{
			_nc.call("sendMessage", null, message);
		}

		protected function onConnect():void 
		{ 		
			_blackboardSO = SharedObject.getRemote("blackboard", _nc.uri, false);
			_blackboardSO.connect(_nc);
		}

		private function _receiveMessage(sender:String, message:String):void
		{
			_controller.appendMessage(sender, message);
		}

		private function onNetStatus(e:NetStatusEvent):void
		{
			switch (e.info.code)
			{
				// Connected to the server
				case "NetConnection.Connect.Success":
					onConnect();
					break;
					
			}
		}

		protected function getCallbacks():Object
		{
			return { };
		}

		protected function isTeacher():Boolean
		{
			return false;
		}

		protected final function get nc():NetConnection
		{
			return _nc;
		}
	
		protected final function get so():SharedObject
		{
			return _blackboardSO;
		}

		protected final function get controller():ChatController
		{
			return _controller;
		}
	}
}
